package com.commerceE.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.commerceE.common.exception.ServiceException;
import com.commerceE.domain.Category;
import com.commerceE.service.CategoryService;
import com.commerceE.util.Constant;

@SessionAttributes({"categoryList"})
@Controller
@RequestMapping("/category")
public class CategoryController {
	
	@Autowired
	private CategoryService categoryService;
	
	@ModelAttribute("categoryList")
	public PagedListHolder populatePagedListHolder() {
	       return new PagedListHolder(); 
    }
	
	@RequestMapping(value = "/listAll", method = RequestMethod.GET)
	public String listAll(boolean flag, String pageType, @ModelAttribute("categoryList")PagedListHolder categoryList, Model model){
		try {
			if (flag) {
				categoryList = new PagedListHolder(categoryService.getAllListOfCategory());
				categoryList.setPageSize(Constant.pageNumber);
				model.addAttribute("categoryList", categoryList);
			}else{
				if ("next".equals(pageType)) {
					categoryList.nextPage();
				}
				else if ("previous".equals(pageType)) {
					categoryList.previousPage();
				}
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return "categoryList";
	}
	
	@RequestMapping(value = "/addNewCategory_Form", method = RequestMethod.GET)
	public String addNewCategory_Form(Model model){
		model.addAttribute(new Category());
		return "newCategory";
	}
	
	@RequestMapping(value = "/addCategory", method = RequestMethod.POST) 
	public String addCategory(@Valid Category category, BindingResult result, Model model){
		if(result.hasErrors()){
			return "newCategory";
		}
		try {
			categoryService.insertCategory(category);
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return "redirect:listAll.do?flag=true";
	}
	
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String defaultCall(Model model){
		model.addAttribute("controllerMessage",
				"This is default method from the CategoryController!");
		return "home";
	}

}
